import TyOverlayex from './TyOverlayex'
import $ from 'jquery'
import Overlay from 'ol/Overlay'

class TyPopup extends TyOverlayex {
  constructor(content, inforWindowOptions) {
    super(inforWindowOptions)
    this.content = content
    if (inforWindowOptions) {
      this.container = inforWindowOptions.container
      this.closedHandler = inforWindowOptions.closedHandler
      this.zIndex = inforWindowOptions.zIndex ? inforWindowOptions.zIndex : 1000
      this.width = inforWindowOptions.width
      this.height = inforWindowOptions.height
      this.positioning = inforWindowOptions.positioning ? inforWindowOptions.positioning : 'top-left'
    }
  }

  createOverlay(opt) {
    const popupOpt = {
      position: this.position,
      element: this.createHtmlElement(), // document.getElementById('marker'),
      stopEvent: false,
      offset: this.offset,
      autoPan: true, // the map is panned when calling setPosition, so that the overlay is entirely visible in the current viewport. The default is false.
      autoPanAnimation: {
        duration: 500// 持续时间
      },
      positioning: this.positioning
    }
    if (opt && $.isPlainObject(opt)) {
      $.extend(true, popupOpt, opt)
    } else {
      $.extend(true, popupOpt, this)
    }
    this.overlay = new Overlay(popupOpt)
    return this.overlay
  }

  createHtmlElement() {
    const createDom = (html) => {
      const dom = $(html).appendTo('body')
      return dom[0]
    }
    if (!this.container) {
      if ($('#popup').length > 0) {
        // 判断popup元素是否存在；
        this.container = $('#popup')[0]
      } else {
        const html = '<div id="popup" class="ol-popup">' +
          '<a href="#" id="popup-closer" class="ol-popup-closer"></a>' +
          '<div id="popup-content"></div>' +
          '</div>'
        this.container = createDom(html)

        $('#popup').css('z-index', this.zIndex)
        $('#popup').css('width', this.width + 'px')
        $('#popup').css('height', this.height + 'px')
        $('#popup-closer').mousedown((evt) => { // 为了防止map.click事件触发，这里用mousedown事件；
          $('#popup-closer').blur()
          // evt.preventDefault();//这个阻止不了map.click
          // evt.stopPropagation();//这个不行；
          // console.log('popup closer clicked');
          this.hide()
          return false// 这个不行；
          // 要用mousedown事件才行；
        })
      }
    }
    // $('#popup').show();
    // $('#popup-content').html(this.content);
    return this.container
  }
  setContent(content) {
    $('#popup-content').empty()
    this.content = content
    $('#popup-content').html(this.content)
  }

  openPopup(olMap, coord, content) {
    if (!this.overlay) {
      olMap.addOverlay(this.createOverlay())
    }
    this.show()
    this.setContent(content)
    this.setPosition(coord)
  }
}

export default TyPopup
